<template>
  <o-modal
    v-model="isShow"
    :title="$srv.getI18nByPath('others.userPrefConfig')"
    :size="[600, 600]"
    :mask="true"
    :tap-close="false"
    :show-footer="true"
    :ok="$srv.getI18nByValue('保存')"
    @on-ok="ok"
    @on-close="hideModal"
  >
    <div slot="content" class="userPrefConfig clearfix">
      <Form
        ref="templateInfoForm"
        :model="userPreferences"
        :label-width="126"
        label-colon
        :rules="ruleCustom"
      >
        <Tabs value="TemplateInfo" name="userPrefConfig">
          <TabPane
            :label="$srv.getI18nByValue('模板信息')"
            name="TemplateInfo"
            tab="userPrefConfig"
          >
            <div class="tempInfoRow">
              <FormItem :label="$srv.getI18nBySrv('title')" prop="title">
                <o-i18n-selector
                  :disabled="false"
                  v-model="userPreferences.title"
                  :placeholder="$srv.getLangPathByValue('请输入模板名')"
                ></o-i18n-selector>
              </FormItem>
              <FormItem :label="$srv.getI18nBySrv('f_type')" class="fType">
                <Select
                  v-model="userPreferences.f_type"
                  :disabled="!isAdministratorRole"
                >
                  <Option
                    v-for="(item, ind) in groupCode"
                    :key="ind"
                    :value="item.value"
                    >{{ item.label }}</Option
                  >
                </Select>
              </FormItem>
              <FormItem
                :label="$srv.getI18nBySrv('f_comment')"
                prop="f_comment"
              >
                <Input v-model="userPreferences.f_comment" clearable> </Input>
              </FormItem>
              <FormItem
                :label="$srv.getI18nBySrv('preview')"
                prop="preview"
                class="previewColor"
              >
                <ColorPicker v-model="userPreferences.preview" alpha />
              </FormItem>
            </div>
          </TabPane>
          <TabPane
            v-for="(tabInfo, tabName) in userPreferences.f_data"
            :key="tabName"
            :label="$srv.getI18nByPath(`others.${tabName}`)"
            :name="tabName"
            tab="userPrefConfig"
          >
            <!-- 大类的if语句：当用户喜好的分类之大类（即对应tabs页签）是global时-->
            <div v-if="tabName === 'global'" class="every_group_option">
              <FormItem
                v-for="(val, key) in tabInfo"
                :key="key"
                :label="$srv.getI18nByPath(`others.${key}`)"
              >
                <Select
                  v-if="key.indexOf('Family') !== -1"
                  v-model="userPreferences.f_data[tabName][key]"
                >
                  <Option
                    v-for="(item, ind) in fontFamilyData"
                    :key="ind"
                    :value="item"
                    >{{ item }}</Option
                  >
                </Select>
              </FormItem>
            </div>
            <!-- 大类的else语句：当用户喜好的分类之大类不是global时 -->
            <template v-else>
              <template v-for="(groupInfo, groupName) in tabInfo">
                <!-- if语句：当分组的键名是nav时，需要多循环一层 -->
                <template v-if="groupName === 'nav'">
                  <template v-for="(navInfo, navKey) in groupInfo">
                    <div :key="navKey">
                      <div class="title_line">
                        <Divider type="vertical" />
                        <span>{{
                          $srv.getI18nByPath(`others.${navKey}`)
                        }}</span>
                      </div>
                      <div class="every_group_option">
                        <FormItem
                          v-for="(val, key) in navInfo"
                          :key="key"
                          :label="$srv.getI18nByPath(`others.${key}`)"
                        >
                          <ColorPicker
                            v-model="
                              userPreferences.f_data[tabName][groupName][
                                navKey
                              ][key]
                            "
                            alpha
                          />
                        </FormItem>
                      </div>
                    </div>
                  </template>
                </template>
                <!-- else语句：当分组的键名不是nav时 -->
                <div v-else :key="groupName">
                  <div class="title_line">
                    <Divider type="vertical" />
                    <span>{{ $srv.getI18nByPath(`others.${groupName}`) }}</span>
                  </div>
                  <div class="every_group_option">
                    <FormItem
                      v-for="(val, key) in groupInfo"
                      :key="key"
                      :label="$srv.getI18nByPath(`others.${key}`)"
                    >
                      <ColorPicker
                        v-model="
                          userPreferences.f_data[tabName][groupName][key]
                        "
                        alpha
                      />
                    </FormItem>
                  </div>
                </div>
              </template>
            </template>
          </TabPane>
        </Tabs>
      </Form>
    </div>
  </o-modal>
  <!-- 一个组件要调用多个相同组件时,传入compBoxInfo对象，让子组件注册在一个组件箱内-->
  <!--例：<xxx :compBoxInfo="GT_compBoxInfo" -->
  <!-- 一个组件要调用多个相同组件时,组件箱内引用实例冲突。不需传入compBoxInfo由组件内部产生实例，只需接收compBoxInfo对象-->
  <!--例：<xxx  @compBoxInfo="set???CompBoxInfo"-->
</template>

<script lang="ts">
import oModal from '@/components/base/modal/o-modal/index.vue';
import {
  bgColorData,
  fontColorData,
  fontFamilyData,
  fontSizeData,
  groupCode,
  ifs,
  N_userPrefTemplate,
  T_srv,
  Tsrv,
  vue
} from './config';

@T_srv.comp({
  components: {
    oModal
  }
})
export default class oUserpref extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  @T_srv.prop() config!: any;

  @T_srv.prop() id!: number;

  @T_srv.ref('templateInfoForm') readonly templateForm!: any;

  /* 组件名 */
  private name: string = 'oUserpref';

  // private funName:string = ''
  private G_compName: string = this.name;

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;
  /* 指挥部 */
  // private GT_command: I_cmd = new T_cmd();

  /* 遮罩 */
  //  public isMask: boolean = false;

  private fontFamilyData: string[] = fontFamilyData();

  private fontSizeData: any = fontSizeData();

  private bgColorData: string[] = bgColorData();

  private fontColorData: Array<string> = fontColorData();

  private groupCode: any = groupCode();

  private userPreferences: N_userPrefTemplate = new N_userPrefTemplate();

  public isShow: boolean = false;

  private oldFormData = {};

  private closeCheck: boolean = false;

  // form校验
  private ruleCustom: any = {
    title: [
      { required: true, validator: this.validateString, trigger: 'blur' }
    ],
    preview: [
      { required: true, validator: this.validateString, trigger: 'change' }
    ]
  };

  private isAdministratorRole: boolean =
    Tsrv.store.getters.SysInfo.roleInfo[0].roleType === 1;

  created() {
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    // this.GT_command.init(this, this.GT_compBoxInfo);
    this.init();
  }

  mounted() {
    /* 向父组件发送实例 */
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    this.$emit('compBoxInfo', this.GT_compBoxInfo);
  }

  destroyed() {
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);
    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
  }

  private init() {
    // 打开弹窗需要在created中执行
    this.show();
    if (!Tsrv.utils.noValue(this.config)) {
      const data =
        this.config?.f_type === 0
          ? Tsrv.TPP.getDefConfig()
          : Tsrv.TPP.getPersonalConfig();
      const obj = data.filter(item => item.id === this.config.id)[0];
      obj['f_data'] = Tsrv.utils.isJSONString(obj['f_data'])
        ? JSON.parse(obj['f_data'])
        : obj['f_data'];
      this.userPreferences = obj;
      this.oldFormData = Tsrv.utils.clone(this.userPreferences, true);
    }
  }

  // 字符串类型输入框校验
  private validateString(rule, value, callback) {
    if (Tsrv.utils.noValue(value)) {
      callback(new Error(Tsrv.getI18nByValue('内容不能为空')));
    } else {
      if (rule?.field === 'title') {
        Tsrv.exists(Tsrv.globalVar.dbType.MYSQL, 'test1_user_prefe', {
          title: { $eq: value }
        }).then(([ok, err]) => {
          if (ok) {
            callback(new Error(Tsrv.getI18nByValue('模板名重复')));
          } else {
            callback();
          }
        });
      }
      callback();
    }
  }

  public show() {
    this.isShow = true;
  }

  public hide() {
    this.isShow = false;
  }

  private ok() {
    this.isEditData(this.userPreferences, this.oldFormData);
    // form校验
    if (this.closeCheck) {
      this.templateForm.validate().then(valid => {
        if (valid) {
          this.$bus.$emit(`modal_${this.id}`, this.userPreferences);
          this.hide();
        }
      });
    } else {
      this.$Message.info('没有数据被更新');
      this.hide();
    }
  }

  private hideModal() {
    this.$bus.$emit(`modal_${this.id}`);
    this.hide();
  }

  private isEditData(newData: Object, oldData: Object) {
    const str1: string = Tsrv.utils.md5(JSON.stringify(newData));
    const str2: string = Tsrv.utils.md5(JSON.stringify(oldData));
    this.closeCheck = str1 !== str2;
  }

  private cloneFormItem(currentData) {
    currentData = Tsrv.utils.clone(this.oldFormData, true);
  }

  // private cancel() {
  //   const that = this;
  //   return new Promise((resolve, reject) => {
  //     this.isEditData(this.userPreferences, this.oldFormData);
  //     if (this.closeCheck) {
  //       this.$Modal.confirm({
  //         title: Tsrv.getI18nByPath('others.isclosed') as string,
  //         content: Tsrv.getI18nByPath('others.isclosed') as string,
  //         onOk: () => {
  //           that.cloneFormItem(that.userPreferences);
  //           resolve(true);
  //         },
  //         onCancel: () => {
  //           reject(null);
  //         }
  //       });
  //     } else {
  //       resolve(true);
  //     }
  //   });
  // }
}
</script>
<style lang="scss" scoped>
.ivu-tabs ::v-deep {
  height: 500px;
  .ivu-tabs-content {
    height: calc(100% - 50px);
    .ivu-tabs-tabpane {
      padding-right: 15px;
      height: 100%;
      overflow-y: auto;
      .ivu-divider {
        width: 2px;
        height: 13px;
        background: $default-hover-font-color;
      }
      .ivu-form-item {
        margin-bottom: 16px;
      }
      &::-webkit-scrollbar {
        width: 6px;
        height: 6px;
      }
      /* 滚动条轨道样式 */
      &::-webkit-scrollbar-track {
        background: transparent;
      }
      /* 滚动条滑块样式 */
      &::-webkit-scrollbar-thumb {
        background: rgba(144, 147, 153, 0.2);
        border-radius: 4px;
      }
      /* 当滑块悬停或活动时的样式 */
      &::-webkit-scrollbar-thumb:hover {
        background: rgba(144, 147, 153, 0.4);
      }
    }
  }
}
.userPrefConfig {
  text-align: left;
  .tempInfoRow {
    display: grid;
    grid-template-columns: 1fr 1fr;
  }
  .previewColor {
    padding-left: 20px;
  }
}
.title_line {
  margin-bottom: 6px;
  height: 30px;
  line-height: 30px;
}
.title_line span {
  font-size: 14px;
}
.every_group_option {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .ivu-form-item {
    margin-left: 12px;
    width: calc(50% - 12px);
  }
}
.color_option {
  display: inline-block;
  margin-right: 5px;
  width: 10px;
  height: 10px;
}
.templateInfoForm {
  padding-right: 40px;
}
</style>
